package first.group.ssh.util;

import java.nio.ByteBuffer;
import java.nio.InvalidMarkException;

public class ByteBufferUtil {
    public static ByteBuffer copyCompatedByteBuffer(ByteBuffer buffer) {
        var newBuffer = ByteBuffer.allocate(buffer.remaining());
        newBuffer.put(buffer);
        newBuffer.position(0);
        buffer.position(buffer.position() - newBuffer.capacity());
        return newBuffer;
    }
    
    public static ByteBuffer copyBuffer(ByteBuffer buffer) {
        var newBuffer = ByteBuffer.allocate(buffer.capacity());
        var position = buffer.position();
        var limit = buffer.limit();
        int mark;
        try {
            buffer.reset();
            mark = buffer.position();
        } catch (InvalidMarkException ex) {
            mark = -1;
        }
        buffer.clear();
        
        newBuffer.put(buffer);
        
        if (mark != -1) {
            buffer.position(mark);
            buffer.mark();
        }
        buffer.position(position);
        buffer.limit(limit);
        return newBuffer;
    }
    
    public static byte[] copyBufferToArray(ByteBuffer buffer) {
        var array = new byte[buffer.remaining()];
        buffer.put(array);
        buffer.position(buffer.position() - array.length);
        return array;
    }
}
